/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.command.call;

import apus.command.AbstractCommand;
import apus.entity.PhoneNumber;
import apus.entity.RealCall;
import apus.exception.BusinessException;
import apus.persistence.CallDAO;
import apus.persistence.PhoneNumberDAO;
import apus.services.ServiceLocator;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * The <code>AddCallCommand</code> class represents command, which adds call.
 * @author  Roman Dyatkovsky
 * @author  Maxim Vasilevsky
 * @since APUS v0.4
 * @see AbstractCommand
 */
public class AddCallCommand extends AbstractCommand{

    private final static String IN_NUMBER = "In number ID";
    private final static String OUT_NUMBER = "Out number ID";
    private final static String DURATION = "Duration";
    private final static String TIME_OF_CALL = "Time of call (dd.mm.yyyy hh:mm:ss)";
    
    
    private final static String[] paramsNames = { IN_NUMBER, OUT_NUMBER, DURATION, TIME_OF_CALL };
    
    public AddCallCommand() {
        super("Add new call");
    }
    
    @Override
    public void execute() {
        CallDAO callDAO = ServiceLocator.getService(CallDAO.class);
        PhoneNumberDAO phoneNumberDAO = ServiceLocator.getService(PhoneNumberDAO.class);
        
        DateFormat df = DateFormat.getDateTimeInstance();
        
        int id_in, id_out, duration;
        Date time;
        
        try {
            id_in = Integer.parseInt(params.get(IN_NUMBER));
            id_out = Integer.parseInt(params.get(OUT_NUMBER));
            duration = Integer.parseInt(params.get(DURATION));
        } catch (NumberFormatException e) {
            throw new BusinessException("Wrong number format",e);
        }   
        
        PhoneNumber in = phoneNumberDAO.read(id_in);
        PhoneNumber out = phoneNumberDAO.read(id_out);
        
        if (in==null||out==null) {
            throw new BusinessException("Phone number not found");
        }
        
        try {
            time = df.parse(params.get(TIME_OF_CALL));
        } catch (ParseException e) {
            throw new BusinessException("Wrong date format",e);
        }
                
        callDAO.create(new RealCall(out, in, duration, time));
    }
    
        @Override
    public List<String> getParamNames() {
        return Arrays.asList(paramsNames);
    }
    
}
